<?php

namespace app\beautiful\model\order;

use app\beautiful\model\finance\SettleOrderModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\order\GoodsOrderItemModel;
use app\beautiful\model\partner\PartnerCommissionModel;
use app\beautiful\model\PartnerModel;
use app\common\model\CommonModel;

use app\beautiful\model\member\MemberModel;
use app\stores\model\order\ChargebackModel;
use TencentCloud\Cpdp\V20190820\Models\OrderItem;
use think\facade\Db;

class GoodsOrderModel extends CommonModel{

    protected  $name = 'beautiful_order';

    protected  $pk   = 'order_id';

    protected $type=[

        'pay_info' => 'array',

    ];

    public function coupon()

    {

        return $this->hasOne(MemberCouponModel::class,'member_coupon_id','member_coupon_id');

    }

    public function member()

    {

        return $this->hasOne(MemberModel::class,'member_id','member_id');

    }


    public function partner()

    {

        return $this->hasOne(PartnerModel::class,'member_id','member_id');

    }
    public function getPayTimeFormatAttr($value,$data){

        return $data['pay_time'] ? date('Y-m-d H:i:s',$data['pay_time']) : '-';

    }

    

    public function getOrderTimeAttr($value,$data){

        return date('Y-m-d H:i:s',$data['add_time']);

    }

    

    public function getDjsTimeAttr($value,$data){

        $t = time();

        $djs = $data['add_time'] + 1800 - $t; //30分钟有效

        return  $djs > 0 ?  $djs : 0;

    }

    

    public function getYouhuiAttr($value,$data){

        $youhui = round(($data['integral_balance'] * 100 + $data['coupon_money'] * 100 + $data['youhui_balance'] * 100)/100,2);

        return $youhui;

    }

    

    public function skus(){

        return  $this->hasMany(GoodsOrderItemModel::class,'order_id','order_id');

    }
    public function item(){

        return  $this->hasOne(GoodsOrderItemModel::class,'order_id','order_id');

    }

    public function partnerCommission(){

        return  $this->hasMany(PartnerCommissionModel::class,'order_id','order_id')->where(['type'=>'普通订单']);

    }

    public function getPayTypeMeanAttr($value,$data)

    {
        $type_means=[
            'weixin'=>'微信支付',
            'platform_money'=>'钱包支付',
            'money'=>'储值卡支付',
            'offline' => '线下补单',
        ];
        if(isset($data['mix_pay_type']) && $data['mix_pay_type']){
            $mix_pay_type = explode(',',$data['mix_pay_type']);
            $str = '';
            for($i=0;$i<count($mix_pay_type);$i++){
                $pay_type = $mix_pay_type[$i];
                if($type_means[$pay_type]){
                    $str.=$type_means[$pay_type].',';
                }
            }
            $str = trim($str,",");
            return $str ?? '-';
        }else{
            return $type_means[$data['pay_type']] ?? '-';
        }
        
        return $type_means[$data['pay_type']] ?? '-';

    }



    public function getStatusMeansAttr( $value,$data)

    {
        $status_means=[

            1=>'待付款',

            2=>'待发货',

            3=>'待收货',

            4=>'待自提',

            8=>'已完成',

            9=>'待配送',

            10=>'待使用',

            11=>'退款中',

            12=>'退款成功',

            13=>'已过期',

            -1=>'已取消',

        ];

        return $status_means[$data['status']] ?? '-';

    }



    public function getOrderTypeMeansAttr($value,$data)

    {

        $order_type_means=[

            'normal'=>'商品订单',

            'pre_sale'=>'预售订单',

            'flash_sale'=>'秒杀订单',

            'pin_tuan'=>'拼团订单',

            'set_meal'=>'套餐订单'

        ];

        return $order_type_means[$data['order_type']] ?? '-';

    }
    public function refundLogs(){

        return  $this->hasMany(OrderRefundModel::class,'order_id','order_id');

    }
    public  function list($where,$order,$page=1,$limit=10){
        $query = Db::name('beautiful_order')->alias('o')
            ->join('beautiful_member m','m.member_id=o.member_id')
            ->when(isset($where['start_time']),function ($query) use ($where){
                $query->where('o.add_time>='.$where['start_time']);
            })
            ->when(isset($where['end_time']),function ($query) use ($where){
                $query->where('o.add_time<='.$where['end_time']);
            })
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['o.shop_id'=>$where['shop_id']]);
            })
            ->when(!empty($where['is_paid']),function ($query) use ($where){
                $query->where(['o.is_paid'=>$where['is_paid']]);
            })
            ->when($where['order_ids'],function ($query) use ($where){
                $query->whereIn('o.order_id',$where['order_ids']);
            })
            ->when(isset($where['is_settle']),function ($query) use ($where){
                $query->where(['o.is_settle'=>$where['is_settle']]);
            })
            ->field("o.refund_money,o.order_sn,o.order_id,o.total_price,o.need_pay,o.member_coupon_id,o.coupon_money,o.integral_balance,o.add_time,o.pay_type,o.order_type,o.pay_time,o.status,m.nick_name,m.mobile,m.face");
        $count=$query->count();
        $list=$query->order($order)
            ->limit($limit)->page($page)
            ->select()
            ->toArray();
        if(!empty($list)){
            foreach ($list as &$v){
                $return = $this->getyouhui($v);
                $v['youhui_price'] = $return['youhui_price'];
                $v['goods_name'] = $return['goods_name'];
                $v['total_num'] = $return['total_num'];
                $v['youhui_name'] = $return['youhui_name'];
                $v['youhui'] = $return['youhui'];
                $v['activity'] = $return['activity'];
                $v['pay_type_means'] = $this->getPayTypeMeanAttr('',$v);
                //商户结算
                $settle = SettleOrderModel::where(['order_id'=>$v['order_id']])->find();
                $v['settle_money'] = $settle?sprintf("%.2f",$settle['settle_money']):0;
                $v['need_pay'] = $v['need_pay'] - $v['refund_money'];
            }
        }
        return compact('count','list');
    }
    public function getyouhui($datas){
        $youhui_name = $goods_name = '';
        $youhui = [];
        $activity = '无';
        //优惠券折扣
        if($datas['member_coupon_id']>0){
            $coupon = MemberCouponModel::with(['couponInfo'])->where(['member_coupon_id'=>$datas['member_coupon_id']])->find();
            if($coupon){
                $coupon = $coupon->toArray();
                $youhui[] = [
                    'discount_name'=>$coupon['couponInfo']['name'],
                    'discount_price'=>$datas['coupon_money']
                ];
                $youhui_name.='/券抵扣';
            }
        }
        //优惠
        if($datas['order_type']=='pin_tuan'){
            $youhui[] = [
                'discount_name'=>'拼团价',
                'discount_price'=>$datas['total_price'] - $datas['need_pay']
            ];
            $youhui_name.='/拼团';
            $activity = '拼团';
        }
        if($datas['order_type']=='flash_sale'){
            $youhui[] = [
                'discount_name'=>'秒杀价',
                'discount_price'=>$datas['total_price'] - $datas['need_pay']
            ];
            $youhui_name.='/秒杀';
            $activity = '秒杀';
        }

        $data = GoodsOrderItemModel::where(['order_id'=>$datas['order_id']])->select();
        //数量
        $total_num = $youhui_price = 0;
        foreach ($data as $k=>$v){
            if($k==0){
                $goods_name.=$v['goods_name'];
            }
            if($k==1){
                $goods_name.='...';
            }
            $total_num += $v['goods_num'];
            //会员折扣
            if($v['vip_discount_type']>0){
                if($v['vip_discount_type'] == 1){
                    $discount_name = $v['discount_detail'].'折';
                }else if($v['vip_discount_type'] == 2){
                    $discount_name = '指定价格';
                }else if($v['vip_discount_type'] == 3){
                    $discount_name = '减价';
                }
                if($youhui_name=='' || ($youhui_name!='' && !strpos('会员折扣',$youhui_name))){
                    $youhui_name.='/会员折扣';
                }
                $youhui[] = [
                    'discount_name'=>$discount_name,
                    'discount_price'=>$v['goods_original_price']-$v['goods_price']
                ];
                $toal_chargeback_num = ChargebackModel::where(['shop_id'=>$v['shop_id'],'order_item_id'=>$v['order_item_id'],'is_delete'=>0])->sum('num');
                $youhui_price += sprintf("%.2f",($v['goods_original_price']-$v['goods_price']) * ($v['goods_num'] - $toal_chargeback_num));
            }
        }
        $return = [
            'goods_name'=>$goods_name,
            'total_num'=>$total_num,
            'youhui_name'=>$youhui_name!=''?substr($youhui_name,1):'',
            'youhui'=>$youhui,
            'activity'=>$activity,
            'youhui_price'=>$youhui_price
        ];

        return $return;
    }

}



